import { _decorator, Color, Component, instantiate, KeyCode, Node, Prefab } from 'cc';
import { CameraControl } from '../Camera/CameraControl';
import { TankManager } from './TankManager';
import { ExplosionManager } from './ExplosionManager';
import { GridVisualizer } from '../Astar/Grid/GridVisualizer';
import { TankType } from '../Enum/TankType';
const { ccclass, property } = _decorator;

@ccclass('GameManager')
export class GameManager extends Component {

    @property
    public numRoundsToWin: number = 5;
    @property
    public startDelay: number = 3;
    @property
    public endDelay: number = 3;
    @property(CameraControl)
    public cameraControl: CameraControl = null;
    @property(Prefab)
    public tankPrefab: Prefab = null;

    @property(GridVisualizer)
    public gridVisualizer: GridVisualizer = null;
    @property([Node])
    public spawnPoints: Node[] = [];
    @property([Color])
    public colors: Color[] = [];


    public tanks: TankManager[] = [];

    private roundNumber: number = 0;
    private startWait: number = 0;
    private endWait: number = 0;
    private roundWinner: TankManager = null;
    private gameWinner: TankManager = null;

    start() {
        this.gridVisualizer.InitGrid();
        let tankmgr0: TankManager = new TankManager(this.colors[0], this.spawnPoints[0], TankType.Player);
        tankmgr0.bindKey(KeyCode.KEY_W, KeyCode.KEY_S, KeyCode.KEY_A, KeyCode.KEY_D, KeyCode.SPACE);
        // let tankmgr1: TankManager = new TankManager(this.colors[1], this.spawnPoints[1], TankType.Player);
        // tankmgr1.bindKey(KeyCode.ARROW_UP, KeyCode.ARROW_DOWN, KeyCode.ARROW_LEFT, KeyCode.ARROW_RIGHT, KeyCode.ENTER);
        let tankmgr1: TankManager = new TankManager(this.colors[1], this.spawnPoints[1], TankType.enemy);
        let tankmgr2: TankManager = new TankManager(this.colors[2], this.spawnPoints[2], TankType.enemy);
        let tankmgr3: TankManager = new TankManager(this.colors[3], this.spawnPoints[3], TankType.enemy);
        this.tanks = [tankmgr0, tankmgr1, tankmgr2, tankmgr3];
        ExplosionManager.getInstance().tanks = this.tanks;
        this.spawnAllTanks();
        this.cameraControl.target = tankmgr0.instance;
    }

    private spawnAllTanks() {
        for (let i = 0; i < this.tanks.length; i++) {
            this.tanks[i].grid = this.gridVisualizer.grid;
            this.tanks[i].instance = instantiate(this.tankPrefab);
            this.tanks[i].instance.setParent(this.node.parent);
            this.tanks[i].playNumber = i + 1;
            this.tanks[i].setup();
            this.tanks[i].Reset();
            
        }
    }

}

